package com.demo.demo.images;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Constants;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

/**
 * Copyright
 *
 * @Author WuHuang
 * @Date 2023/5/12
 */
public class ImageValidator {
    public static String validateImage(String imageUrl, int width, int height) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(2000); // 设置连接超时时间为2秒
            connection.setReadTimeout(2000); // 设置读取数据超时时间为2秒

            BufferedImage img = ImageIO.read(connection.getInputStream());

            if (img == null) {
                return "图片URL为空"; // 图片URL为空
            }

            // 判断图片尺寸是否符合要求
            if (img.getWidth() != width || img.getHeight() != height) {
                return "符合要求";
            }
            return null;
        } catch (Exception e) {
            return "出现异常，图片验证失败"; // 出现异常，图片验证失败
        }
    }

    public static void main(String[] args) throws IOException {
//        URL url = new URL("https://images.lululemon.com/is/image/lululemon/LU9AX9S_058129_1");
//        String s = extractFilename("https://images.lululemon.com/is/image/lululemon/LU9AX9S_058129_1.jpg");
//        System.out.println(s);
//        InetAddress ipAddress = InetAddress.getByName(url.getHost());
//        System.out.println(ipAddress.getHostAddress());

//        String a = "https://images.lululemon.com/is/image/lululemon/LW9DU7S_056436_1";
//        System.out.println(validateImagev2(a,1800,2160));
//        System.out.println(  isValidDecimal("102.22111111"));
//        System.out.println(  isValidDecimal("asdsad"));
//        System.out.println(  isDecimal("10.299"));
//        System.out.println(  isDecimal("10000"));
//        InputStream templateStream = new URL("https://sh-staging-changyi-wecom20-01.oss-cn-shanghai.aliyuncs.com/template/%E5%A4%B1%E8%B4%A5%E5%9B%BE%E7%89%87%E5%88%97%E8%A1%A8%E6%A8%A1%E7%89%88.xlsx").openStream();
        String url = "https://images.lululemon.com/is/image/lululemon/LW4CAJS_3151_1";

        validateImagev3(url,1800,2160);
    }

    public  static boolean isValidDecimal(String strNum) {
        // 定义正则表达式，表示小数且小数点后有两位数字
        String pattern = "^[0-9]+(\\.[0-9]+)?$";
        // 判断字符串是否匹配正则表达式
        return !Pattern.matches(pattern, strNum);
    }

    public static boolean isDecimal(String strNum) {
        // 定义小数的正则表达式，小数点后最多两位
        String pattern = "^\\d+(\\.\\d{1,2})?$";
        // 判断该字符串是否匹配小数的正则表达式
        return !Pattern.matches(pattern, strNum);
    }

    public static String extractFilename(String originalUrl) {
        String extension = "png";
//        // 获取最后一个 "." 出现的位置
//        int dotIndex = originalUrl.lastIndexOf(".");
//        // 如果 "." 存在并且不在最后一位，则获取文件后缀
//        if (dotIndex > 0 && dotIndex < originalUrl.length() - 1) {
//            extension = originalUrl.substring(dotIndex + 1);
//        }
        if (originalUrl.matches(".*\\.(jpg|jpeg|png|gif)$")) {
            // 如果URL以jpg、jpeg、png或gif结尾，则截取文件扩展名
            extension = originalUrl.replaceAll("^.*\\.(.*)$", "$1");
        }
        return extension;
    }

    public  static String validateImagev2(String imageUrl, int width, int height) {
        try {
            URL url = new URL(imageUrl);
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(2000); // 设置连接超时时间为2秒
            connection.setReadTimeout(2000); // 设置读取数据超时时间为2秒
            // 检查响应头中的Content-Type字段
            String contentType = connection.getHeaderField("Content-Type");
            if (contentType == null || !contentType.startsWith("image/")) {
                return "URL不是图片"; // URL不是图片
            }
            BufferedImage img = ImageIO.read(connection.getInputStream());

            if (img == null) {
                return "图片URL为空"; // 图片URL为空
            }

            // 判断图片尺寸是否符合要求
            if (img.getWidth() != width || img.getHeight() != height) {
                return "不符合要求";
            }
            return null;
        } catch (Exception e) {
            return "出现异常，图片验证失败"; // 出现异常，图片验证失败
        }
    }

    public  static String validateImagev3(String imageUrl, int width, int height) {
        BufferedImage img = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(imageUrl);
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(5000); // 设置连接超时时间为2秒
            connection.setReadTimeout(5000); // 设置读取数据超时时间为2秒
            // 检查响应头中的Content-Type字段
            String contentType = connection.getHeaderField("Content-Type");
            if (contentType == null || !contentType.startsWith("image/")) {
                return "URL不是图片"; // URL不是图片
            }
            inputStream = connection.getInputStream();
            img = ImageIO.read(inputStream);
            if (img == null) {
                return "图片URL为空"; // 图片URL为空
            }

            // 判断图片尺寸是否符合要求
            if (!(img.getWidth() >= width - 20 && img.getWidth() <= width + 20)
                    || !(img.getHeight() >= height - 20 && img.getHeight() <= height + 20)) {
                return "不符合要求";
            }
            return null;
        } catch (Exception e) {
            return "不符合要求";
        }finally {
            IoUtil.close(inputStream);
            if (img != null){
                img.flush();
            }
        }
    }

    private String appendErrMsg(String err, String errMsg) {
        if (StrUtil.isEmpty(errMsg)) {
            return err;
        }
        return err + (StrUtil.isNotEmpty(err) ? "," : Constants.EMPTY) + errMsg;
    }
}

